//
//  SelectPayController.swift
//  CreateMyCode
//
//  Created by zhibao on 2024/2/7.
//

import UIKit
class SelectPayController: SecSuperController,SDCycleScrollViewDelegate {
    var pinglunArray = [[String:String]]()
    var priceTitleLabel = UILabel()
    var btns = [UIButton]();
    var payDataArray = [String]()
    var selectIndex = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        UserInfoManager.shared().getUserInfoData { sucess in
            
        }
        pinglunArray.append(
            [
                "title":"用了一段时间，感觉效果还不错，希望能在多一些模版，这样更能有选择权了。",
                "autor":"我是土豆",
                "from":"来自周用户的评论"
            ]
        )
        pinglunArray.append(
            [
                "title":"找了好久，前几天才找到这一款，挺符合我现在的工作场景，非常感谢。",
                "autor":"单身上班贵族",
                "from":"来自年用户的评论"
            ]
        )
        pinglunArray.append(
            [
                "title":"公司最近老是让自定义二维码，太麻烦了，今天终于找到一款神器！",
                "autor":"地铁109号",
                "from":"来自月会员评论"
            ]
        )
        pinglunArray.append(
            [
                "title":"创作起来很简单，不用在找网站制作，大大提高了工作效率，还能直接分享，真好！",
                "autor":"周呈祥",
                "from":"来自微博用户评论"
            ]
        )
        payDataArray.append("com.yuliang.zhou")
        payDataArray.append("com.yuliang.year")
        self.gk_navigationBar.isHidden = true
        self.initView()
    }
    
    fileprivate func initView(){
        let bgImgView = UIImageView(frame: CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT))
        bgImgView.image = UIImage(named: "firstPay.jpg")
        bgImgView.contentMode = .scaleAspectFill
        self.view.addSubview(bgImgView)
        
        let cancelBtn = UIButton(type: .custom)
        cancelBtn.setImage(UIImage(named: "pay_quxiao"), for: .normal)
        self.view.addSubview(cancelBtn)
        cancelBtn.addTarget(self, action: #selector(cancelClick), for: .touchUpInside)
        cancelBtn.snp.makeConstraints { make in
            make.left.equalTo(pixw(p:15))
            make.top.equalTo(statusBarHeight() + pixw(p: 10))
        }
        
        let repayBtn = UIButton(type: .custom)
        repayBtn.setTitle("  恢复购买  ", for: .normal)
        repayBtn.titleLabel?.font = MY_SCALE_RegularFONT(12)
        repayBtn.setTitleColor(MYOrange, for: .normal)
        self.view.addSubview(repayBtn)
        repayBtn.addTarget(self, action: #selector(repayClick), for: .touchUpInside)
        repayBtn.snp.makeConstraints { make in
            make.right.equalTo(pixw(p: -15))
            make.centerY.equalTo(cancelBtn)
        }

        let xieyiLabel = YYLabel()
        xieyiLabel.centerX = SCREEN_WIDTH / 2
        xieyiLabel.preferredMaxLayoutWidth = SCREEN_WIDTH - pixw(p: 60)
        xieyiLabel.numberOfLines = 0
        xieyiLabel.lineBreakMode = .byWordWrapping
        self.view.addSubview(xieyiLabel)
        let string = NSMutableString()
        string.append("用户协议")
        string.append("      |     ")
        string.append("隐私协议")
        string.append("      |      ")
        string.append("订阅协议")
        let yhrange = string.range(of: "用户协议")
        let ysrange = string.range(of: "隐私协议")
        let dyrange = string.range(of: "订阅协议")
        
        let attrui = NSMutableAttributedString(string: string as String)
        attrui.yy_font = MY_SCALE_RegularFONT(11)
        attrui.yy_color = UIColor.white
        attrui.yy_setTextHighlight(yhrange, color: UIColor.white, backgroundColor: UIColor.clear) { containerView, text, range, rect in
            let webViewContoller = WebViewController(title: "用户协议", withUrl: "https://docs.qq.com/doc/DRkR6VUxYU0xwTFln")
            self.navigationController?.pushViewController(webViewContoller, animated: true)
        }
        
        attrui.yy_setTextHighlight(ysrange, color: UIColor.white, backgroundColor: UIColor.clear) { containerView, text, range, rect in
            let webViewContoller = WebViewController(title: "隐私协议", withUrl: "https://docs.qq.com/doc/DRnB3clFBbXJFcWti")
            self.navigationController?.pushViewController(webViewContoller, animated: true)
        }
        
        attrui.yy_setTextHighlight(dyrange, color: UIColor.white, backgroundColor: UIColor.clear) { containerView, text, range, rect in
            let webViewContoller = WebViewController(title: "订阅协议", withUrl: "https://docs.qq.com/doc/DRlhIR2hnYm9Ib3dM")
            self.navigationController?.pushViewController(webViewContoller, animated: true)
        }
        xieyiLabel.attributedText = attrui
        xieyiLabel.textAlignment = .center
        xieyiLabel.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.bottom.equalTo(self.view).offset(-30)
        }
        
        let contiueBtn = UIButton(type: .custom)
        contiueBtn.backgroundColor = MYBlue
        contiueBtn.layer.cornerRadius = pixw(p: 23)
        contiueBtn.setTitle("继续", for: .normal)
        contiueBtn.setTitleColor(UIColor.white, for: .normal)
        contiueBtn.titleLabel?.font = MY_SCALE_SemiboldFONT(16)
        contiueBtn.addTarget(self, action: #selector(toPay), for: .touchUpInside)
        self.view.addSubview(contiueBtn)
        contiueBtn.snp.makeConstraints { make in
            make.left.equalTo(pixw(p: 30))
            make.right.equalTo(pixw(p: -30))
            make.bottom.equalTo(xieyiLabel.snp.top).offset(-62)
            make.height.equalTo(pixw(p: 46))
        }
        
        var tempView = UIView()
        tempView = contiueBtn
        let onlyPay = DWKeychainTool.getItemForKey("onlypay")
        if(onlyPay == nil){
           let payView = UIView()
            payView.layer.cornerRadius = pixw(p: 20)
            payView.layer.borderColor = UIColor.white.cgColor
            payView.layer.borderWidth = pixw(p: 0.5)
            self.view.addSubview(payView)
            payView.snp.makeConstraints { make in
                make.left.right.equalTo(contiueBtn)
                make.bottom.equalTo(contiueBtn.snp.top).offset(pixw(p: -15))
                make.height.equalTo(pixw(p: 40))
            }
            
            let payTitleLabel = UILabel()
            payTitleLabel.text = "试用已开启"
            payTitleLabel.tag = 10000
            payTitleLabel.textColor = MYOrange
            payTitleLabel.font = MY_SCALE_SemiboldFONT(12)
            payView.addSubview(payTitleLabel)
            payTitleLabel.snp.makeConstraints { make in
                make.left.equalTo(15)
                make.top.bottom.equalTo(payView)
            }
            
            let payBtn = UIButton(type: .custom)
            payBtn.setImage(UIImage(named: "pay_open"), for: .normal)
            payBtn.tag = 100
            payBtn.addTarget(self, action: #selector(payBtnClick(sender:)), for: .touchUpInside)
            payView.addSubview(payBtn)
            payBtn.snp.makeConstraints { make in
                make.width.equalTo(34)
                make.right.equalTo(-15)
                make.top.bottom.equalTo(payView)
            }
            tempView = payView
        }
        
        let cancelLabel = UILabel()
        cancelLabel.text = "可随时取消订阅"
        cancelLabel.textAlignment = .center
        cancelLabel.font = MY_SCALE_FONT(16)
        cancelLabel.textColor = MYColor.color(withHexString: "ffffff")
        self.view.addSubview(cancelLabel)
        cancelLabel.snp.makeConstraints { make in
            make.left.equalTo(15)
            make.right.equalTo(-15)
            make.bottom.equalTo(tempView.snp.top).offset(-20)
        }
        tempView = cancelLabel
        
        priceTitleLabel = UILabel()
        priceTitleLabel.font = MY_SCALE_FONT(16)
        priceTitleLabel.textAlignment = .center
        priceTitleLabel.numberOfLines = 0
        priceTitleLabel.lineBreakMode = .byWordWrapping
        if(payDataArray.count > 0){
            if onlyPay != nil {
                Helper.setLabelInfo([["仅","￥128.00/年"],[UIColor.white,MYColor.color(withHexString: "F9C948")],[MY_SCALE_SemiboldFONT(15),MY_SCALE_SemiboldFONT(15)]], with: priceTitleLabel)
                selectIndex = 1
            }else{
                Helper.setLabelInfo([["试用3天,之后","￥8.00/周"],[UIColor.white,MYColor.color(withHexString: "F9C948")],[MY_SCALE_SemiboldFONT(15),MY_SCALE_SemiboldFONT(15),MY_SCALE_RegularFONT(15)]], with: priceTitleLabel)
            }
            
        }
        self.view.addSubview(priceTitleLabel)
        priceTitleLabel.snp.makeConstraints { make in
            make.left.equalTo(10)
            make.right.equalTo(-10)
            make.bottom.equalTo(tempView.snp.top).offset(-15)
        }
        
        let cycleScrollVIew = SDCycleScrollView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 168), shouldInfiniteLoop: true, imageNamesGroup: ["s","s","s","s"])
        cycleScrollVIew?.backgroundColor = UIColor.clear
        cycleScrollVIew?.infiniteLoop = true
        cycleScrollVIew?.autoScroll = true
        cycleScrollVIew?.autoScrollTimeInterval = 4
        cycleScrollVIew?.bannerImageViewContentMode = .scaleAspectFit
        cycleScrollVIew?.pageControlStyle = SDCycleScrollViewPageContolStyleClassic
        cycleScrollVIew?.pageControlBottomOffset = 10
        self.view.addSubview(cycleScrollVIew!)
        cycleScrollVIew!.snp.makeConstraints({ make in
            make.left.right.equalTo(self.view)
            make.bottom.equalTo(priceTitleLabel.snp.top).offset(-30)
            make.height.equalTo(pixw(p: 80) + 88)
        })
        cycleScrollVIew?.delegate = self
        cycleScrollVIew?.scrollDirection = .horizontal
        
        let tipLabel = UILabel()
        tipLabel.text = "**二维码生成神器**"
        tipLabel.font = MY_SCALE_SemiboldFONT(24)
        tipLabel.textColor = MYOrange
        self.view.addSubview(tipLabel)
        tipLabel.snp.makeConstraints { make in
            make.bottom.equalTo(cycleScrollVIew!.snp.top).offset(-50)
            make.centerX.equalTo(self.view)
        }
        
        let logoImgView = UIImageView(image: UIImage(named: "com_icon"))
        self.view.addSubview(logoImgView)
        logoImgView.snp.makeConstraints { make in
            make.centerX.equalTo(self.view)
            make.width.height.equalTo(70)
            make.bottom.equalTo(tipLabel.snp.top).offset(-30)
        }
        logoImgView.layer.masksToBounds = true
        logoImgView.layer.cornerRadius = 10
    }
    
    @objc fileprivate func cancelClick(){
        self.gotoHome()
    }
    
    @objc fileprivate func repayClick(){
        QMUITips.showLoading("...恢复中...", detailText: "...正在获取支付信息...", in: self.view)
        IAPShare.sharedHelper().iap.restoreProducts { payment, error in
            QMUITips.hideAllTips()
            let number = payment?.transactions.count ?? 0
            if(number < 1){
                QMUITips.showError("无可恢复购买的项目")
                return
            }
            
            var flag = false
            for transaction in payment!.transactions{
                if transaction.transactionState == .restored && flag == false {
                    flag = true
//                    let productIdentifier = transaction.payment.productIdentifier
                    self.verifyPurchaseWithPaymentTransaction(transaction: transaction)
                }
            }
        }
    }
    
    @objc fileprivate func toPay(){
        let payID = payDataArray[selectIndex] 
        QMUITips.showLoading("...购买中...", detailText: "...查询信息中...", in: self.view)
        IAPShare.sharedHelper().iap.requestProducts { request, response in
            if response?.products.count ?? 0 > 0 {
                var product:SKProduct?
                for pro in response!.products{
                    if pro.productIdentifier == payID {
                        product = pro
                        break
                    }
                }
                
                if let tempPro = product {
                    IAPShare.sharedHelper().iap.buyProduct(tempPro) { trans in
                        if((trans?.error) != nil){
                            QMUITips.hideAllTips()
                            QMUITips.showError("...购买失败...", detailText: "...请稍后再试...")
                        }else if trans?.transactionState == .purchased{
                            
                            //交易验证
                            guard let recepitURL = Bundle.main.appStoreReceiptURL else { return }
                            let receipt = try? Data(contentsOf: recepitURL)
                            if(receipt == nil){
                                QMUITips.hideAllTips()
                                QMUITips.showError("...购买失败...", detailText: "...请稍后再试...")
                                return
                            }
                            
                            var time = Helper.getTime(.zhou)
                            if payID == "com.yuliang.yue" {
                                time = Helper.getTime(.yue)
                            }else if payID == "com.yuliang.ji" {
                                time = Helper.getTime(.ji)
                            }else if payID == "com.yuliang.year" {
                                time = Helper.getTime(.nian)
                            }
                            QMUITips.hideAllTips()
                            QMUITips.showSucceed("...购买成功...", detailText: "...恭喜您成为Vip会员...")
                            DWKeychainTool.saveItem(payID, key: "id")
                            DWKeychainTool.saveItem(time, key: "vip")
                            UserInfoManager.shared().getUserInfoData { sucess in
                                
                            }
                            self.gotoHome()
                        }
                    }
                }else{
                    QMUITips.hideAllTips()
                    QMUITips.showError("...购买失败...", detailText: "...请稍后再试...")
                }
                
            }else{
                QMUITips.hideAllTips()
                QMUITips.showError("...购买失败...", detailText: "...请稍后再试...")
            }
        }
    }
    
    @objc fileprivate func payBtnClick(sender:UIButton){
        let tempLabel = sender.superview?.viewWithTag(10000) as! UILabel
        if sender.tag == 100 {
            sender.tag = 101
            sender.setImage(UIImage(named: "pay_close"), for: .normal)
            tempLabel.text = "适用已关闭"
            Helper.setLabelInfo([["仅","￥128.00/年"],[UIColor.white,MYColor.color(withHexString: "F9C948")],[MY_SCALE_SemiboldFONT(15),MY_SCALE_SemiboldFONT(15)]], with: priceTitleLabel)
        }else{
            sender.tag = 100
            sender.setImage(UIImage(named: "pay_open"), for: .normal)
            tempLabel.text = "适用已开启"
            Helper.setLabelInfo([["试用3天,之后","￥8.00/周"],[UIColor.white,MYColor.color(withHexString: "F9C948")],[MY_SCALE_SemiboldFONT(15),MY_SCALE_SemiboldFONT(15),MY_SCALE_RegularFONT(15)]], with: priceTitleLabel)
        }
        selectIndex = sender.tag - 100
    }
    
    func gotoHome(){
        let barController = TabBarController()
        func keyWindow() -> UIWindow {
               if #available(iOS 15.0, *) {
                   let keyWindow = UIApplication.shared.connectedScenes
                       .map({ $0 as? UIWindowScene })
                       .compactMap({ $0 })
                       .first?.windows.first ?? UIWindow()
                   return keyWindow
               }else {
                   let keyWindow = UIApplication.shared.windows.first ?? UIWindow()
                   return keyWindow
               }
           }
        keyWindow().rootViewController = barController
    }
    
    fileprivate func verifyPurchaseWithPaymentTransaction(transaction:SKPaymentTransaction){
        QMUITips.showLoading("...恢复中...", detailText: "...正在验证支付信息...", in: self.view)
        guard let recepitURL = Bundle.main.appStoreReceiptURL else { return }
        let receipt = try? Data(contentsOf: recepitURL)
        if(receipt == nil){
            QMUITips.hideAllTips()
            QMUITips.showError("恢复失败", detailText: "无可恢复项目")
            return
        }
        let idKey = DWKeychainTool.getItemForKey("id") as? String
        var time = Helper.getTime(.zhou)
        if idKey == "com.yuliang.yue" {
            time = Helper.getTime(.yue)
        }else if idKey == "com.yuliang.ji" {
            time = Helper.getTime(.ji)
        }else if idKey == "com.yuliang.year" {
            time = Helper.getTime(.nian)
        }
        DWKeychainTool.saveItem(time, key: "vip")
        UserInfoManager.shared().getUserInfoData { sucess in
            
        }
        self.gotoHome()
    }
    
    
}
extension SelectPayController{
    func customCollectionViewCellClass(for view: SDCycleScrollView!) -> AnyClass! {
        return UICollectionViewCell.self
    }
    
    func setupCustomCell(_ cell: UICollectionViewCell!, for index: Int, cycleScrollView view: SDCycleScrollView!) {
        for subView in cell.contentView.subviews {
            if subView.tag == 1000 {
                subView.removeFromSuperview()
            }
        }
        
        let startView = UIView()
        startView.tag = 1000
        cell.contentView.addSubview(startView)
        startView.snp.makeConstraints { make in
            make.top.equalTo(18)
            make.centerX.equalTo(cell.contentView)
        }
        
        var tempImgView:UIImageView?
        for i in 0 ..< 5 {
            let imgView = UIImageView(image: UIImage(named: "comon_star"))
            startView.addSubview(imgView)
            imgView.snp.makeConstraints { make in
                if(tempImgView != nil){
                    make.left.equalTo(tempImgView!.snp.right).offset(4)
                }else{
                    make.left.equalTo(0)
                }
                if i == 4 {
                    make.right.equalTo(startView)
                }
                
                make.top.bottom.equalTo(startView)
            }
            tempImgView = imgView
        }
        
        let titleLabel = UILabel()
        titleLabel.text = pinglunArray[index]["title"]
        titleLabel.font = MY_SCALE_RegularFONT(12)
        titleLabel.textColor = MYOrange
        titleLabel.tag = 1000
        titleLabel.numberOfLines = 2
        titleLabel.textAlignment = .center
        titleLabel.lineBreakMode = .byWordWrapping
        cell.contentView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(startView.snp.bottom).offset(17)
            make.left.equalTo(58)
            make.width.equalTo(SCREEN_WIDTH - 116)
        }
        
        let autorLabel = UILabel()
        autorLabel.text = pinglunArray[index]["autor"]
        autorLabel.font = MY_SCALE_RegularFONT(11)
        autorLabel.textColor = MYOrange
        autorLabel.tag = 1000
        autorLabel.numberOfLines = 0
        autorLabel.textAlignment = .center
        autorLabel.lineBreakMode = .byWordWrapping
        cell.contentView.addSubview(autorLabel)
        autorLabel.snp.makeConstraints { make in
            make.top.equalTo(titleLabel.snp.bottom).offset(10)
            make.left.equalTo(58)
            make.width.equalTo(SCREEN_WIDTH - 116)
        }
        
        let fromLabel = UILabel()
        fromLabel.text = pinglunArray[index]["from"]
        fromLabel.font = MY_SCALE_RegularFONT(12)
        fromLabel.textColor = MYOrange
        fromLabel.tag = 1000
        fromLabel.numberOfLines = 0
        fromLabel.textAlignment = .center
        fromLabel.lineBreakMode = .byWordWrapping
        cell.contentView.addSubview(fromLabel)
        fromLabel.snp.makeConstraints { make in
            make.top.equalTo(autorLabel.snp.bottom).offset(5)
            make.left.equalTo(58)
            make.width.equalTo(SCREEN_WIDTH - 116)
        }
    }
}
